import 'dart:async';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/interact_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/video_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_interact_info_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_list_entity.dart';
import 'package:flutter_taotaoshipin/model/drama_main_info_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_collect_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_collect_rm_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_praise_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_praise_rm_entity.dart';
import 'package:flutter_taotaoshipin/model/interact_user_share_entity.dart';
import 'package:flutter_taotaoshipin/model/video_geturl_entity.dart';
import 'package:flutter_taotaoshipin/player/flick_multi_manager.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';

import 'recommend_state.dart';

class RecommendController extends GetxController {
  final RecommendState state = RecommendState();

  late PageController pageController;
  late FlickMultiManager flickMultiManager;

  @override
  void onInit() {
    super.onInit();

    // 初始化page
    pageController = PageController();
    // 初始化播放器
    flickMultiManager = FlickMultiManager();

    // 获取所有推荐
    loadDramaPlay();

    // 获取签到详情
    _loadUserSignInDetailData();
    // 获取任务列表
    _loadUserTaskListData();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    pageController.dispose();
    super.onClose();
  }

  void onPageChanged(int page) {
    state.pageIndex = page;
  }

  /// 点赞按钮
  void userPraiseBtnClicked(int index) async {
    // 交互数据
    var dramaInteractInfoEntity = state.dramaInteractInfoEntityMap[index];

    if (dramaInteractInfoEntity?.praiseBool == true) {
      // 取消点赞
      var entity = await loadPraiseRmData(index);
      if (entity != null) {
        if (entity.state == 1) {
          dramaInteractInfoEntity?.praise =
              _decrementCount(dramaInteractInfoEntity.praise);
          dramaInteractInfoEntity?.praiseBool = false;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      // 点赞
      var entity = await loadPraiseData(index);
      if (entity != null) {
        if (entity.state == 1) {
          dramaInteractInfoEntity?.praise =
              _incrementCount(dramaInteractInfoEntity.praise);
          dramaInteractInfoEntity?.praiseBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    }
  }

  /// 收藏按钮
  void userCollectBtnClicked(int index) async {
    // 交互数据
    var dramaInteractInfoEntity = state.dramaInteractInfoEntityMap[index];

    if (dramaInteractInfoEntity?.collectBool == true) {
      // 取消收藏
      var entity = await loadCollectRmData(index);
      if (entity != null) {
        if (entity.state == 1) {
          dramaInteractInfoEntity?.collect =
              _decrementCount(dramaInteractInfoEntity.collect);
          dramaInteractInfoEntity?.collectBool = false;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      // 收藏
      var entity = await loadCollectData(index);
      if (entity != null) {
        if (entity.state == 1) {
          dramaInteractInfoEntity?.collect =
              _incrementCount(dramaInteractInfoEntity.collect);
          dramaInteractInfoEntity?.collectBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    }
  }

  /// 分享按钮
  void userShareBtnClicked(int index) async {
    var newText = GlobalConfig.systemShare;
    ShareResult result = await Share.shareWithResult(newText);
    if (result.status == ShareResultStatus.success) {
      var entity = await loadShareData(index);
      if (entity != null) {
        if (entity.state == 1) {
          // 交互数据
          var dramaInteractInfoEntity = state.dramaInteractInfoEntityMap[index];

          dramaInteractInfoEntity?.share =
              _incrementCount(dramaInteractInfoEntity.share);
          dramaInteractInfoEntity?.shareBool = true;
          update(['dramaInteractInfoEntity']);
        }
        if (entity.msg != null && entity.msg!.isNotEmpty) {
          EasyLoading.showToast(entity.msg!);
        }
      }
    } else {
      EasyLoading.showToast('分享失败');
    }
  }

  bool showFuliRed() {
    bool hasSignIn = state.signInDetailEntity != null &&
            DateUtil.isToday(state.signInDetailEntity!.ctime! * 1000)
        ? true
        : false;
    bool hasDone =
        state.taskList.firstWhereOrNull((element) => element.state == 0) !=
            null;
    return !hasSignIn || !hasDone;
  }

  Future<bool> startLoadVideoUrlData(int index) async {
    // 主剧id
    var dramaId = state.recommendDramaList[index];

    // 主剧信息
    var mainInfoEntity = state.mainInfoEntityMap[index];
    if (mainInfoEntity == null) {
      mainInfoEntity = await _loadMainInfoData(dramaId);
      state.mainInfoEntityMap[index] = mainInfoEntity ?? DramaMainInfoEntity();
    }
    // 分集信息
    var dramaListEntityList = state.dramaListEntityListMap[index];
    if (dramaListEntityList == null) {
      dramaListEntityList = await _loadDramaListData(dramaId);
      state.dramaListEntityListMap[index] = dramaListEntityList;
    }
    // 交互信息
    var dramaInteractInfoEntity = state.dramaInteractInfoEntityMap[index];
    if (dramaInteractInfoEntity == null) {
      dramaInteractInfoEntity = await _loadDramaInteractInfoData(dramaId);
      state.dramaInteractInfoEntityMap[index] = dramaInteractInfoEntity;
    }

    // 视频地址
    var videoUrl = state.videoUrlMap[index];
    if (videoUrl == null) {
      videoUrl = await fullLoadVideoUrlData(index);
      state.videoUrlMap[index] = videoUrl ?? VideoGeturlEntity();
    }

    return true;
  }

  /// 加载视频地址
  Future<VideoGeturlEntity?> fullLoadVideoUrlData(int index) async {
    var entity = state.dramaListEntityListMap[index]!.first;

    // 用户交互
    // curSort = entity.sort!;
    // curListId = entity.id!;

    var mainInfoEntity = state.mainInfoEntityMap[index];
    return await loadVideoUrlData(
        entity.id!, entity.vid!, mainInfoEntity!.isSelf!);
  }

  /// 获取视频地址和视频信息
  Future<VideoGeturlEntity?> loadVideoUrlData(
    int dramaId,
    String vId,
    int isSelf,
  ) async {
    VideoGeturlEntity? entity;
    try {
      var result =
          await VideoDao.getUrl(dramaId: dramaId, vId: vId, isSelf: isSelf);
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return entity;
  }

  /// 获取主剧详情
  Future<DramaMainInfoEntity?> _loadMainInfoData(int dramaId) async {
    DramaMainInfoEntity? entity;
    try {
      var result = await DramaDao.getDramaMainInfo(dramaId, '');
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return entity;
  }

  /// 获取分集列表数据
  Future<List<DramaListEntity>> _loadDramaListData(int dramaId) async {
    List<DramaListEntity> list = [];
    try {
      var result = await DramaDao.getDramaList(dramaId);
      if (result.code == 0) {
        if (result.data != null) {
          list = result.data!;
        }
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {}
    return list;
  }

  /// 主剧交互信息
  Future<DramaInteractInfoEntity> _loadDramaInteractInfoData(
      int dramaId) async {
    DramaInteractInfoEntity entity = DramaInteractInfoEntity();
    try {
      var result = await DramaDao.interactInfo(dramaId: dramaId);
      if (result.code == 0) {
        if (result.data != null) {
          entity = result.data!;
        }
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 点赞
  Future<InteractUserPraiseEntity?> loadPraiseData(int index) async {
    InteractUserPraiseEntity? entity;
    // 剧集信息
    int dramaId = state.recommendDramaList[index];
    var dramaListEntity = state.dramaListEntityListMap[index]!.first;

    try {
      var result = await InteractDao.userPraise(
        dramaId: dramaId,
        sort: dramaListEntity.sort!,
        listId: dramaListEntity.id!,
      );
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 取消点赞
  Future<InteractUserPraiseRmEntity?> loadPraiseRmData(int index) async {
    InteractUserPraiseRmEntity? entity;
    // 剧集信息
    int dramaId = state.recommendDramaList[index];
    var dramaListEntity = state.dramaListEntityListMap[index]!.first;

    try {
      var result = await InteractDao.userPraiseRm(
        dramaId: dramaId,
        sort: dramaListEntity.sort!,
        listId: dramaListEntity.id!,
      );
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 收藏
  Future<InteractUserCollectEntity?> loadCollectData(int index) async {
    InteractUserCollectEntity? entity;
    // 剧集信息
    int dramaId = state.recommendDramaList[index];
    var dramaListEntity = state.dramaListEntityListMap[index]!.first;

    try {
      var result = await InteractDao.userCollect(
        dramaId: dramaId,
        sort: dramaListEntity.sort!,
        listId: dramaListEntity.id!,
      );
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 取消收藏
  Future<InteractUserCollectRmEntity?> loadCollectRmData(int index) async {
    InteractUserCollectRmEntity? entity;
    // 剧集信息
    int dramaId = state.recommendDramaList[index];
    var dramaListEntity = state.dramaListEntityListMap[index]!.first;

    try {
      var result = await InteractDao.userCollectRm(
        dramaId: dramaId,
        sort: dramaListEntity.sort!,
        listId: dramaListEntity.id!,
      );
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  /// 分享
  Future<InteractUserShareEntity?> loadShareData(int index) async {
    InteractUserShareEntity? entity;
    // 剧集信息
    int dramaId = state.recommendDramaList[index];
    var dramaListEntity = state.dramaListEntityListMap[index]!.first;

    try {
      var result = await InteractDao.userShare(
        dramaId: dramaId,
        sort: dramaListEntity.sort!,
        listId: dramaListEntity.id!,
      );
      if (result.code == 0) {
        entity = result.data;
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
    return entity;
  }

  Future<void> loadDramaPlay() async {
    try {
      var result = await DramaDao.play();
      if (result.code == 0) {
        if (result.data != null) {
          state.recommendDramaList = result.data!.dramaId!;
          // state.recommendDramaList.shuffle(); // 随机排列
          // 更新
          update(['recommendDramaList']);
        }
      } else {
        if (result.message.isNotEmpty) {
          EasyLoading.showToast(result.message);
        }
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
  }

  int _incrementCount(int? count) {
    if (count == null) {
      return 0;
    } else {
      return count + 1;
    }
  }

  int _decrementCount(int? count) {
    if (count == null) {
      return 0;
    } else {
      return count - 1;
    }
  }

  /// 获取用户签到详情
  Future<void> _loadUserSignInDetailData() async {
    try {
      var result = await InteractDao.userSignInDetail();
      if (result.code == 0) {
        state.signInDetailEntity = result.data;
      }
    } catch (_) {}
  }

  /// 获取任务列表
  Future<void> _loadUserTaskListData() async {
    try {
      var result = await InteractDao.userTaskList();
      if (result.code == 0) {
        if (result.data != null) {
          if (GlobalConfig.isReview == 1) {
            state.taskList = result.data!
                .where((element) => !element.taskName!.contains('好评'))
                .toList();
          } else {
            state.taskList = result.data!;
          }
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {}
  }
}
